
const db = require('db');
const { getTokenInof } = require('tools/token');
const isLeader = require('tools/isLeader');
const log = require('tools/log');

module.exports = async ctx => {
    const { connection, run } = db.init();
    try {
        ctx.status = 200;
        ctx.body = {
            list: await queryEntry(ctx, run),
            pagination: await pagination(ctx, run)
        };
    } catch (error) {
        ctx.status = 500;
        ctx.body = error;        
        log('---------------------------------------------------')
        console.log(error)
    }
    connection.end();
}

async function queryEntry(ctx, run) {
    const body = ctx.request.body;
    const sqlStr = `
    SELECT * 
    FROM settlementEntry
    LEFT JOIN orders ON orders.id = settlementEntry.ordersId
    WHERE (settlementId is NULL)
    ${toWhereStin(body.column, body.filters)}
    ${permission(ctx)}
    ${toSorterStin(body.sorter, `ORDER BY orders.completionTime DESC`)}
    ${toLimit(body.pagination)}
    `

    const result = await run(sqlStr);
    if (result.err) {
        throw result.err
    }

    return result.rows;
}

async function pagination(ctx, run) {
    const body = ctx.request.body;
    const sqlStr = `
    SELECT COUNT(*) as total
    FROM settlementEntry
    LEFT JOIN orders ON orders.id = settlementEntry.ordersId
    WHERE (settlementId is NULL)
    ${toWhereStin(body.column, body.filters)}
    ${permission(ctx)}
    `
    
    const result = await run(sqlStr);
    if (result.err) {
        throw result.err
    }

    return {
        ...body.pagination,
        total: result.rows[0].total
    };
}

// ------------------------------------------------------------------------------------------------------

/** 分页语句 */
function toLimit(pagination) {
    const { current = 1, pageSize = 10 } = pagination || {};
    return `LIMIT ${(current - 1) * pageSize},${pageSize}`;
}

/** 排序 */
function toSorterStin(sorter, def) {
    if (!(sorter && sorter.order)) return def;
    if (sorter.order === 'ascend') {
        return `ORDER BY ${sorter.columnKey} ASC`;
    } if (sorter.order === 'descend') {
        return `ORDER BY ${sorter.columnKey} DESC`;
    } else {
        return def
    }
}

/** 筛选 */
function toWhereStin(column, filters) {
    const arr = [];
    for (let key in filters) {
        const f = filters[key];
        const c = column.filter(e => e.key === key)[0];
        if (c && f && c.form && c.form.type) {
            switch (c.form.type) {
                case 'date':
                    arr.push(`${key}>="${f[0]}" AND ${key}<="${f[1]}"`);
                    break;

                default:
                    arr.push(f.map(i => `${key} LIKE "%${i}%"`).join(' OR '));
                    break;
            }
        }
    }

    const ret = arr.length > 0 ? `AND ${arr.map(e => `(${e})`).join(` AND `)}` : ''
    return ret;
}

/** 数据权限 */
function permission(ctx) {
    const userInfo = getTokenInof(ctx.header.authorization).userInfo;
    const isL = isLeader(userInfo);
    
    if (isL) return '';

    return `AND (orders.commercialSpecialistId=${userInfo.userid})`
}

